package com.sq.service.minio.impl;


import com.sq.dto.FileDto;
import com.sq.service.minio.IFileMinioService;
import com.sq.util.DateToStringPath;
import io.minio.*;
import io.minio.errors.MinioException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.Base64;
import java.util.Date;


@Service
@Slf4j
public class IFileMinioServiceImpl implements IFileMinioService {
    @Value("${minio.url}")
    String url;
    @Value("${minio.accessKey}")
    String accessKey;
    @Value("${minio.secretKey}")
    String secretKey;

    @Override
    public String upload(FileDto fileDto) {
        String result = "";
        String fileName = DateToStringPath.getDateToStringPath(new Date())+fileDto.getFileName()+"."+fileDto.getFileType();
        log.info("=============文件保存路径: {}", fileName);
        MinioClient minioClient =
                MinioClient.builder()
                        .endpoint(url)
                        .credentials(accessKey,secretKey)
                        .build();
        createBucket(minioClient,fileDto.getBucketName());
        if(!fileDto.getBase64().isEmpty()){
            result=uploadByBase64(minioClient,fileDto,fileName);
        }else if(!fileDto.getFilePath().isEmpty()){
            result=uploadByFilePath(minioClient,fileDto,fileName);
        }else if(fileDto.getMultipartFile()!=null){
            result=uploadByInputStream(minioClient,fileDto,fileName);
        }else {
            result="上传失败，请选择base64,file,文件路径，其中一种方式进行上传";
        }
        return result;
    }
    public void createBucket(MinioClient minioClient,String bucketName) {
        try {
            // 检查桶是否存在
            boolean isExist = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
            if(!isExist) {
                // 创建新的桶，使用地区 'us-east-1'
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
            }
        } catch (MinioException e) {
            // 处理MinIO异常
            e.printStackTrace();
        } catch (Exception e) {
            // 处理其他异常
            e.printStackTrace();
        }
    }
    @Override
    public InputStream getFile(GetObjectArgs getObjectArgs) {
        MinioClient minioClient =
                MinioClient.builder()
                        .endpoint(url)
                        .credentials(accessKey,secretKey)
                        .build();
        InputStream inputStream=null;
        try {
            inputStream = minioClient.getObject(getObjectArgs);
            return inputStream;
        } catch (Exception e){
            log.error(e.getMessage());
            return null;
        }
    }


    private String uploadByFilePath(MinioClient minioClient,FileDto fileDto,String fileName) {
        try {
            minioClient.uploadObject(
                    UploadObjectArgs.builder()
                            .bucket(fileDto.getBucketName())
                            .object(fileName)
                            .filename(fileDto.getFilePath())
                            .build());
        } catch (Exception e) {
           log.error(e.getMessage());
        }
        return fileName;
    }
    private String uploadByInputStream(MinioClient minioClient,FileDto fileDto,String fileName) {

        try {
            InputStream inputStream=fileDto.getMultipartFile().getInputStream();
            PutObjectArgs putObjectArgs = PutObjectArgs.builder()
                    .bucket(fileDto.getBucketName()) // 存储桶名称
                    .object(fileName) // 对象名称
                    .contentType("image/jpeg") // 内容类型，根据实际情况设置
                    .stream(inputStream,inputStream.available(),-1) // 数据流及长度
                    .build();
            minioClient.putObject(putObjectArgs);
        } catch (Exception e) {
            log.error(e.getMessage());
        }
        return fileName;
    }
    private String uploadByBase64(MinioClient minioClient,FileDto fileDto,String fileName) {
        byte[] data = Base64.getDecoder().decode(fileDto.getBase64());
        try {
            PutObjectArgs putObjectArgs = PutObjectArgs.builder()
                    .bucket(fileDto.getBucketName()) // 存储桶名称
                    .object(fileName) // 对象名称
                    .contentType("image/jpeg") // 内容类型，根据实际情况设置
                    .stream(new ByteArrayInputStream(data), data.length, -1) // 数据流及长度
                    .build();
            minioClient.putObject(putObjectArgs);
        }catch (Exception e) {
            log.error(e.getMessage());
        }
        return fileName;
    }
}
